/*
 *  Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com).
 *  <p>
 *  Licensed under the GNU Lesser General Public License 3.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  <p>
 * https://www.gnu.org/licenses/lgpl.html
 *  <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.lanswon.icc.gateway.handler;

import com.lanswon.icc.common.core.constant.RedisKeyConstant;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * 验证码生成逻辑处理类
 */
@Slf4j
@Component
@AllArgsConstructor
public class SmsCodeHandler implements HandlerFunction<ServerResponse> {

	private final RedisTemplate redisTemplate;


	@Override
	public Mono<ServerResponse> handle(ServerRequest serverRequest) {

		//生成验证码
		String text = RandomStringUtils.randomNumeric(6);
		//保存验证码信息
		String randomStr = serverRequest.queryParam("mobile").get();
		log.info("手机验证码:[{}]",text);
		redisTemplate.opsForValue().set(RedisKeyConstant.DEFAULT_CODE_KEY + randomStr, text, 60, TimeUnit.SECONDS);



		return ServerResponse
			.status(HttpStatus.OK)
			.contentType(MediaType.TEXT_PLAIN)
			.body(BodyInserters.fromObject(text));
	}

	public static void main(String[] args) {
		int i = ThreadLocalRandom.current().nextInt(10);
		System.out.println(i);
	}
}
